package com.gome.transactiontree.sample.case3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gome.transactiontree.api.Transaction;
import com.gome.transactiontree.api.TransactionManager;

@Service
public class BusinessBProxy {

	private static final Logger LOG = LoggerFactory.getLogger(BusinessBProxy.class);
	
	@Autowired
	private BusinessB businessB;
	
	@Autowired
	private TransactionManager transactionManager;
	
	public String b1(final String txid, final String p2) {
		LOG.info("BusinessBProxy.b1({},{})", txid, p2);
		
		final Transaction transaction = transactionManager.getTransation();
		ExecutorService es = Executors.newFixedThreadPool(10);
		Future<String> future = es.submit(new Callable<String>() {
			public String call() throws Exception {
				transactionManager.setTransation(transaction);
				try {
					return businessB.b1(txid, p2);
				} finally {
					transactionManager.getTransactionRepository().clearCache();
				}
			}
		});
		
		try {
			return future.get();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
	}
}